<?php
$page_title = '仪表板 - 考务管理系统';

// 开启会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

// 数据库连接
try {
    require_once 'database.php';
    $db_connected = isset($conn) && $conn instanceof mysqli;
} catch (Exception $e) {
    error_log("数据库连接失败: " . $e->getMessage());
    $db_connected = false;
}

if (!$db_connected) {
    $_SESSION['error_message'] = "数据库连接失败，请联系管理员";
    header('Location: user_home.php');
    exit();
}

// 初始化统计数据
$stats = [
    'total_exams' => 0,
    'total_rooms' => 0,
    'total_staff' => 0,
    'serving_staff' => 0,
    'retired_staff' => 0,
    'total_signups' => 0,
    'pending_signups' => 0,
    'approved_signups' => 0,
    'total_arrangements' => 0,
    'online_staff' => 0
];

// 获取统计数据 - 使用更安全的查询方式
try {
    // 考试项目统计 - 检查表是否存在
    $table_check = $conn->query("SHOW TABLES LIKE 'exam_projects'");
    if ($table_check && $table_check->num_rows > 0) {
        $exam_stats_result = $conn->query("SELECT COUNT(*) as total_exams FROM exam_projects");
        if ($exam_stats_result) {
            $exam_data = $exam_stats_result->fetch_assoc();
            $stats['total_exams'] = $exam_data['total_exams'] ?? 0;
        }
    }

    // 教室统计
    $table_check = $conn->query("SHOW TABLES LIKE 'exam_rooms'");
    if ($table_check && $table_check->num_rows > 0) {
        $room_stats_result = $conn->query("SELECT COUNT(*) as total_rooms FROM exam_rooms");
        if ($room_stats_result) {
            $room_data = $room_stats_result->fetch_assoc();
            $stats['total_rooms'] = $room_data['total_rooms'] ?? 0;
        }
    }

    // 员工统计
    $table_check = $conn->query("SHOW TABLES LIKE 'staff'");
    if ($table_check && $table_check->num_rows > 0) {
        $staff_stats_result = $conn->query("SELECT
            COUNT(*) as total_staff,
            SUM(CASE WHEN serving = 1 THEN 1 ELSE 0 END) as serving_staff,
            SUM(CASE WHEN serving = 0 THEN 1 ELSE 0 END) as retired_staff
            FROM staff");
        if ($staff_stats_result) {
            $staff_data = $staff_stats_result->fetch_assoc();
            $stats['total_staff'] = $staff_data['total_staff'] ?? 0;
            $stats['serving_staff'] = $staff_data['serving_staff'] ?? 0;
            $stats['retired_staff'] = $staff_data['retired_staff'] ?? 0;
        }
    }

    // 报名统计
    $table_check = $conn->query("SHOW TABLES LIKE 'exam_signups'");
    if ($table_check && $table_check->num_rows > 0) {
        $signup_stats_result = $conn->query("SELECT
            COUNT(*) as total_signups,
            SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_signups,
            SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved_signups
            FROM exam_signups");
        if ($signup_stats_result) {
            $signup_data = $signup_stats_result->fetch_assoc();
            $stats['total_signups'] = $signup_data['total_signups'] ?? 0;
            $stats['pending_signups'] = $signup_data['pending_signups'] ?? 0;
            $stats['approved_signups'] = $signup_data['approved_signups'] ?? 0;
        }
    }

    // 安排统计
    $table_check = $conn->query("SHOW TABLES LIKE 'exam_arrangements'");
    if ($table_check && $table_check->num_rows > 0) {
        $arrangement_stats_result = $conn->query("SELECT COUNT(*) as total_arrangements FROM exam_arrangements");
        if ($arrangement_stats_result) {
            $arrangement_data = $arrangement_stats_result->fetch_assoc();
            $stats['total_arrangements'] = $arrangement_data['total_arrangements'] ?? 0;
        }
    }

    // 在线员工统计
    $table_check = $conn->query("SHOW TABLES LIKE 'staff'");
    if ($table_check && $table_check->num_rows > 0) {
        // 检查online_status字段是否存在
        $column_check = $conn->query("SHOW COLUMNS FROM staff LIKE 'online_status'");
        if ($column_check && $column_check->num_rows > 0) {
            $online_staff_result = $conn->query("SELECT COUNT(*) as online_count FROM staff WHERE serving = 1 AND online_status = 1");
            if ($online_staff_result) {
                $online_data = $online_staff_result->fetch_assoc();
                $stats['online_staff'] = $online_data['online_count'] ?? 0;
            }
        }
    }

} catch (Exception $e) {
    error_log("获取统计数据时发生错误: " . $e->getMessage());
    // 继续使用默认值
}

// 获取最近的考试项目
$recent_exams_result = null;
try {
    $table_check = $conn->query("SHOW TABLES LIKE 'exam_projects'");
    if ($table_check && $table_check->num_rows > 0) {
        $recent_exams_result = $conn->query("SELECT exam_name, exam_date, start_time, end_time FROM exam_projects ORDER BY exam_date DESC, start_time DESC LIMIT 5");
    }
} catch (Exception $e) {
    error_log("获取最近考试项目时发生错误: " . $e->getMessage());
}

// 获取最近的报名
$recent_signups_result = null;
try {
    $table_check1 = $conn->query("SHOW TABLES LIKE 'exam_signups'");
    $table_check2 = $conn->query("SHOW TABLES LIKE 'exam_projects'");
    if ($table_check1 && $table_check1->num_rows > 0 && $table_check2 && $table_check2->num_rows > 0) {
        $recent_signups_result = $conn->query("SELECT
            es.participant_name,
            ep.exam_name,
            es.signup_date,
            es.status
            FROM exam_signups es
            JOIN exam_projects ep ON es.exam_id = ep.exam_id
            ORDER BY es.signup_date DESC
            LIMIT 5");
    }
} catch (Exception $e) {
    error_log("获取最近报名时发生错误: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- 统一样式 -->
    <link rel="stylesheet" href="css/unified-style.css">

    <style>
    .main-content {
        padding-top: 20px;
        padding-bottom: 40px;
    }

    .page-header {
        text-align: center;
        padding: 20px;
        margin-bottom: 0;
    }

    .page-title {
        color: #2c3e50;
        margin-bottom: 10px;
        font-size: 2.5rem;
        font-weight: 600;
    }

    .page-subtitle {
        color: #7f8c8d;
        font-size: 1.1rem;
        margin-bottom: 0;
    }

    .info-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 15px;
    }

    .info-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #eee;
    }

    .info-item:last-child {
        border-bottom: none;
    }

    .info-label {
        display: flex;
        align-items: center;
        font-weight: 500;
        color: #495057;
    }

    .info-label i {
        margin-right: 8px;
        width: 16px;
    }

    .info-value {
        font-weight: 600;
        color: #2c3e50;
        font-size: 1.1rem;
    }

    .card {
        border: none;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .card-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-bottom: none;
        padding: 15px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .card-header i {
        margin-right: 8px;
    }

    .card-body {
        padding: 20px;
    }

    .list-group-item {
        border: none;
        padding: 15px 0;
        border-bottom: 1px solid #eee;
    }

    .list-group-item:last-child {
        border-bottom: none;
    }

    .btn {
        border-radius: 6px;
        padding: 12px 24px;
        font-weight: 500;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
    }

    .btn i {
        margin-bottom: 5px;
    }

    .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <?php
    if (file_exists('common/navigation.php')) {
        include_once 'common/navigation.php';
    } else {
        // 简单的导航栏备用方案
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="dashboard.php">考务管理系统</a>
                    <div class="navbar-nav ms-auto">
                        <a class="nav-link" href="dashboard.php">仪表板</a>
                        <a class="nav-link" href="logout.php">退出</a>
                    </div>
                </div>
              </nav>';
    }
    ?>

    <!-- 主要内容 -->
    <div class="container main-content">
        <!-- 页面标题 -->
        <div class="card">
            <div class="page-header">
                <h1 class="page-title">仪表板</h1>
                <p class="page-subtitle">考务管理系统概览</p>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="row mb-4">
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="fas fa-clipboard-list fa-3x text-primary mb-3"></i>
                        <h3><?php echo intval($stats['total_exams']); ?></h3>
                        <p class="text-muted mb-0">考试项目</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="fas fa-door-open fa-3x text-success mb-3"></i>
                        <h3><?php echo intval($stats['total_rooms']); ?></h3>
                        <p class="text-muted mb-0">考试教室</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="fas fa-users fa-3x text-info mb-3"></i>
                        <h3><?php echo intval($stats['serving_staff']); ?></h3>
                        <p class="text-muted mb-0">在职员工</p>
                        <small class="text-muted">在线: <?php echo intval($stats['online_staff']); ?></small>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="fas fa-user-check fa-3x text-warning mb-3"></i>
                        <h3><?php echo intval($stats['pending_signups']); ?></h3>
                        <p class="text-muted mb-0">待审核报名</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 详细统计 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-chart-pie"></i> 员工统计
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-users text-primary"></i> 员工总数
                                </span>
                                <span class="info-value"><?php echo intval($stats['total_staff']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-user-check text-success"></i> 在职员工
                                </span>
                                <span class="info-value"><?php echo intval($stats['serving_staff']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-user-times text-secondary"></i> 退休员工
                                </span>
                                <span class="info-value"><?php echo intval($stats['retired_staff']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-circle text-success"></i> 在线员工
                                </span>
                                <span class="info-value"><?php echo intval($stats['online_staff']); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-chart-bar"></i> 报名统计
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-clipboard-list text-primary"></i> 总报名数
                                </span>
                                <span class="info-value"><?php echo intval($stats['total_signups']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-clock text-warning"></i> 待审核
                                </span>
                                <span class="info-value"><?php echo intval($stats['pending_signups']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-check-circle text-success"></i> 已批准
                                </span>
                                <span class="info-value"><?php echo intval($stats['approved_signups']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-calendar-check text-info"></i> 考试安排
                                </span>
                                <span class="info-value"><?php echo intval($stats['total_arrangements']); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 最近活动 -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-calendar"></i> 最近考试项目
                    </div>
                    <div class="card-body">
                        <?php if ($recent_exams_result && $recent_exams_result->num_rows > 0): ?>
                            <div class="list-group list-group-flush">
                                <?php while ($exam = $recent_exams_result->fetch_assoc()): ?>
                                    <div class="list-group-item border-0 px-0">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h6 class="mb-1"><?php echo htmlspecialchars($exam['exam_name'] ?? '未知考试'); ?></h6>
                                                <small class="text-muted">
                                                    <i class="fas fa-calendar"></i> <?php echo htmlspecialchars($exam['exam_date'] ?? '未知日期'); ?>
                                                    <?php if (!empty($exam['start_time']) && !empty($exam['end_time'])): ?>
                                                        <i class="fas fa-clock ms-2"></i> <?php echo substr($exam['start_time'], 0, 5); ?>-<?php echo substr($exam['end_time'], 0, 5); ?>
                                                    <?php endif; ?>
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-muted text-center">暂无考试项目</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-user-plus"></i> 最近报名
                    </div>
                    <div class="card-body">
                        <?php if ($recent_signups_result && $recent_signups_result->num_rows > 0): ?>
                            <div class="list-group list-group-flush">
                                <?php while ($signup = $recent_signups_result->fetch_assoc()): ?>
                                    <div class="list-group-item border-0 px-0">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h6 class="mb-1"><?php echo htmlspecialchars($signup['participant_name'] ?? '未知参与者'); ?></h6>
                                                <p class="mb-1 text-muted small"><?php echo htmlspecialchars($signup['exam_name'] ?? '未知考试'); ?></p>
                                                <small class="text-muted">
                                                    <i class="fas fa-clock"></i>
                                                    <?php
                                                    if (!empty($signup['signup_date'])) {
                                                        echo date('m-d H:i', strtotime($signup['signup_date']));
                                                    } else {
                                                        echo '未知时间';
                                                    }
                                                    ?>
                                                </small>
                                            </div>
                                            <div>
                                                <?php
                                                $status_class = 'badge bg-secondary';
                                                $status_text = '未知状态';
                                                switch ($signup['status'] ?? '') {
                                                    case 'pending':
                                                        $status_class = 'badge bg-warning';
                                                        $status_text = '待审核';
                                                        break;
                                                    case 'approved':
                                                        $status_class = 'badge bg-success';
                                                        $status_text = '已批准';
                                                        break;
                                                    case 'rejected':
                                                        $status_class = 'badge bg-danger';
                                                        $status_text = '已拒绝';
                                                        break;
                                                }
                                                ?>
                                                <span class="<?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                            </div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-muted text-center">暂无报名记录</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- 快速操作 -->
        <div class="card mt-4">
            <div class="card-header">
                <i class="fas fa-bolt"></i> 快速操作
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3 mb-3">
                        <a href="create_exam_project.php" class="btn btn-primary w-100">
                            <i class="fas fa-plus-circle"></i><br>
                            创建考试项目
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <a href="add_room.php" class="btn btn-success w-100">
                            <i class="fas fa-door-open"></i><br>
                            添加教室
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <a href="arrange_rooms_invigilators.php" class="btn btn-info w-100">
                            <i class="fas fa-calendar-check"></i><br>
                            安排监考
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <a href="signup_management.php" class="btn btn-warning w-100">
                            <i class="fas fa-user-check"></i><br>
                            管理报名
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <?php
    // 关闭数据库连接
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
    ?>
</body>
</html>